/**
 * 配置
 * */
package org.zmhhxl.sample3.oauth2.a.configure;

//自定义登录
// UsernamePasswordAuthenticationToken(userDetails, password, authorities)


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.stereotype.Component;

@Component
//@Configuration
public class RememberMeConfig {

   @Value("${custom.security.rememberMeTokenKey}")
   private String rememberMeTokenKey;  //密钥用于加密和解密记住我令牌

   @Bean
   RememberMeServices rememberMeServices(UserDetailsService userDetailsService) {
      // 使用SHA256作为编码和匹配算法，提高安全性
      // PersistentTokenBasedRememberMeServices
      // AlwaysRememberMeServices 无期限的记住我
      TokenBasedRememberMeServices.RememberMeTokenAlgorithm encodingAlgorithm = TokenBasedRememberMeServices.RememberMeTokenAlgorithm.SHA256;

      // 使用可配置的密钥，而不是硬编码加上类名
      TokenBasedRememberMeServices rememberMe = new TokenBasedRememberMeServices(rememberMeTokenKey, userDetailsService, encodingAlgorithm);

      // 默认情况下，Remember Me的checkbox的name属性应与此匹配
      rememberMe.setParameter("remember-me");
      rememberMe.setCookieName("rememberMeCookie");
      rememberMe.setTokenValiditySeconds(86400);  // 86400秒 = 1天 设置令牌有效期为1天
      // 持久化令牌存储 对应实例化PersistentTokenBasedRememberMeServices
      //rememberMe.setPersistentTokenRepository(new CustomPersistentTokenRepository());
      // 统一使用SHA256算法
      rememberMe.setMatchingAlgorithm(encodingAlgorithm);

      return rememberMe;
   }

}
